
//
//  ZDQSearchViewController.m
//  CoreDataAddressBook
//
//  Created by dllo on 15/11/20.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "ZDQSearchViewController.h"
#import "ZDQAddressTableViewCell.h"
#import "ZDQCoreDataManager.h"
#import "AddressBook.h"
#import "ZDQMoreAddressViewController.h"

@interface ZDQSearchViewController()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain) UISearchBar *searchBar;
@property(nonatomic, retain) UITableView *tableView;
@property(nonatomic, retain) ZDQCoreDataManager *manager;
@property(nonatomic, retain) NSArray *array;

@end

@implementation ZDQSearchViewController

- (void)dealloc {
    
    [_searchBar release];
    [_tableView release];
    [_array release];
    [super dealloc];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self.tableView reloadData];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(20, 20, 250, 30)];
    self.searchBar.tintColor = [UIColor lightGrayColor];
    self.searchBar.placeholder = @"搜索名字";
    self.searchBar.keyboardType = UIKeyboardAppearanceDefault;
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.delegate = self;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.rowHeight = 150;
    [_tableView release];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    
    self.manager = [ZDQCoreDataManager defaults];
    NSLog(@"url ========== %@", [self.manager applicationDocumentsDirectory]);
    
}



#pragma mark searchbar的方法
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
//    
//    NSLog(@"%@", searchBar.text);
//    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"AddressBook"];
//    
//    // Specify criteria for filtering which objects to fetch
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], searchBar.text];
//    //给请求添加约束
//    request.predicate = predicate;
//    
//    //通过某个key给数组排序
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//    
//    //
//    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
//    
//    
//    NSError *error;
//    
//    self.array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
//    
//    NSLog(@"%ld", self.array.count);
//    NSLog(@"%@", self.array);
//    
//    if (self.array.count == 0) {
//        
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"系统通知" message:@"未查询到结果" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *Action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//           
//            
//            
//        }];
//        
//        [alertController addAction:Action];
//        
//        [self presentViewController:alertController animated:YES completion:^{
//            
//            
//        }];
//    } else {
//        
//        [self.tableView reloadData];
//        
//    }
//
//    
//    
//}
//

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    NSLog(@"%@", searchBar.text);
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"AddressBook"];
    
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], searchBar.text];
        //给请求添加约束
        request.predicate = predicate;
    
        //通过某个key给数组排序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    
        //
        [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    
        NSError *error;
    
        self.array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
    
        NSLog(@"%ld", self.array.count);
        NSLog(@"%@", self.array);
    
        if (self.array.count == 0) {
    
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"系统通知" message:@"未查询到结果" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *Action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
    
    
            }];
    
            [alertController addAction:Action];
    
            [self presentViewController:alertController animated:YES completion:^{
                
                
            }];
            
        }
    
    [self.tableView reloadData];

    
}


#pragma mark -- dataSource和delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.array.count;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *reuse = @"reuse";
    ZDQAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[ZDQAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse] autorelease];
        
    }
    
    AddressBook *Add = self.array[indexPath.row];
    NSString *str = [NSString stringWithFormat:@"姓名:  %@", Add.name];
    cell.nameLabel.text = str;
    NSString *Str = [NSString stringWithFormat:@"性别:  %@", Add.sex];
    cell.sexLabel.text = Str;
    NSString *string = [NSString stringWithFormat:@"学号:  %@", Add.number];
    cell.numberLabel.text = string;
    
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZDQMoreAddressViewController *moreVC = [[ZDQMoreAddressViewController alloc] init];
    [self.navigationController pushViewController:moreVC animated:YES];
    [moreVC release];
    
    AddressBook *Add = self.array[indexPath.row];
    moreVC.Add = Add;

    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
